package com.itdfq.redislock.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author GocChin
 * @Date 2021/8/21 14:53
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description:
 */
@RestController
public class TestController {
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private Redisson  redisson;





    /**
     * 传统方法，可能有bug  需要添加定时器 或者死循环  延长时间
     *
     *
     */
    @GetMapping("/deduct_stock")
    public void decutStock(){
        String LockKey="product_001";

        String clientId = UUID.randomUUID().toString();
        try {
            //获取锁
            Boolean result = redisTemplate.opsForValue().setIfAbsent(LockKey, clientId, 10, TimeUnit.SECONDS);
            if (!result){
                return  ;
            }
            Integer sum = Integer.parseInt((String) redisTemplate.opsForValue().get("sum"));
            if (sum>0){
                int realSum=sum-1;
                redisTemplate.opsForValue().set("sum",realSum);
                System.out.println("购买成功，剩余库存为："+realSum);
            }else{
                System.out.println("卖完了");
            }
        } finally {
            if (clientId.equals(redisTemplate.opsForValue().get(LockKey))){
                redisTemplate.delete(LockKey);
            }
        }
    }
    /**
     * 新方法 使用Redisson
     *
     * lock - 业务 -unlock
     */

    @GetMapping("/deduct_stock2")
    public void decutStock2(){
        String LockKey="product_001";

        String clientId = UUID.randomUUID().toString();
        //获取锁
        RLock lock = redisson.getLock(LockKey);
        try {
            lock.lock(20,TimeUnit.SECONDS);
            Integer sum = Integer.parseInt((String) redisTemplate.opsForValue().get("sum"));
            if (sum>0){
                int realSum=sum-1;
                redisTemplate.opsForValue().set("sum",realSum);
                System.out.println("购买成功，剩余库存为："+realSum);
            }else{
                System.out.println("卖完了");
            }
        } finally {
            lock.unlock();
        }
    }


}
